/**
 * @file task_test.c
 * @brief 
 * @author Tome (zigbee86@163.com)
 * @date 2021-01-05
 */
 

#include "OSAL.h" 
#include "osal_log.h"

#include "hal_led.h"

#include "stdio.h"
#include "task_time.h"
#include "task_test_led.h"


 
/****************************************************************************************************************************** 
                                                            const
*******************************************************************************************************************************/












/****************************************************************************************************************************** 
                                                            typedef
*******************************************************************************************************************************/













/****************************************************************************************************************************** 
                                                            MICRO
*******************************************************************************************************************************/




/****************************************************************************************************************************** 
                                                            declearation
*******************************************************************************************************************************/



static uint8 Test_TaskID;
static uint8_t rttBuffer[32];
static uint8_t write_len = 0;

/****************************************************************************************************************************** 
                                                            defination
*******************************************************************************************************************************/






/* <!------  HAL LED TEST INTERFACE START ------>*/
#define HAL_LED_DEBUG 1
#if HAL_LED_DEBUG == 1

/* log define */
#define HAL_LED_LOG( s ) _hal_led_log(s,__FILE__,__LINE__, 0 )
#define HAL_LED_LOG_ERROR( s ) _hal_led_log(s,__FILE__,__LINE__,1)
void _hal_led_log(uint8_t *buf, uint8_t *file, uint32_t line, uint8_t tip)
{
    LOG_RAW("\x1B[0m");
    LOG_RAW( "[HAL_LED_DEBUG] : " );
    LOG_RAW( buf );

    if( tip )
    {

        LOG_RAW( " ------> " );
        LOG_RAW("FILE: ");
        LOG_RAW(file);
        LOG_RAW(" LINE: %d",line);

    }
    LOG_RAW( "\r\n" );
   
}

// print help tip
void hal_led_test_print_help()
{

    HAL_LED_LOG("<------------------------ HAL LED HELP ------------------------>");
    HAL_LED_LOG(" CommandName: F   -- LED FLASH");
    HAL_LED_LOG(" USAGE: F LED_NUM PERIOD DUTY CYCLE");
    HAL_LED_LOG(" eg : F 0 1000 50 3       ");
    HAL_LED_LOG(" CommandName: B   -- LED BREATH ");
    HAL_LED_LOG(" USAGE: B LED_NUM PERIOD DUTY CYCLE ");
    HAL_LED_LOG(" eg : B 0 1000 50 3       ");
    HAL_LED_LOG(" If you want to operate all the LEDs, let the LED_NUM is X ");
    HAL_LED_LOG(" If you want to breath/flash leds forever, let the CYCLE is 255 ");
    HAL_LED_LOG("<----------------------------- END ---------------------------->");


}

// judge char num
uint8_t hal_led_test_is_num(uint8_t a)
{

    if( a >= '0' && a <= '9' ) return 1;
    else return 0;

}



void hal_led_test_by_uart( uint8_t *buf, uint8_t len )
{

    uint16_t priod = 0;
    uint16_t cycle = 0;
    uint8_t led_num = 0;
    uint8_t mode = 0;
    uint8_t duty = 0;
    uint8_t status = 0;
    uint8_t flag = 0;
    uint8_t i = 0 ;
    uint8_t j = 0 ;


    //skip space
    for(; i<len; i++)
    {
        if( buf[i] != ' ' )
        {
            break;
        }

    }

    if( i==len )
    {
        hal_led_test_print_help();
        return;
    }

    //help printf
    if( buf[i] == 'H' )
    {

        hal_led_test_print_help();

        return ;

    }
    
//    if( buf[i] == 's' )
//    {
//        HalLedEnterSleep();
//        HAL_LED_LOG("LED ENTER SLEEP");
//        return;
//    }
//    
//    if( buf[i] == 'e' )
//    {
//        HalLedExitSleep();
//        HAL_LED_LOG("LED EXIT SLEEP");
//        return ;
//    }
    
    if( buf[i] == 'z')
    {
        HalLedSet(HAL_LED_4,HAL_LED_MODE_ON);
        HAL_LED_LOG("LED SET ON");
        return;
    }
    
    if( buf[i] == 'a' )
    {
        HalLedSet(HAL_LED_4,HAL_LED_MODE_OFF);
        HAL_LED_LOG("LED SET OFF");
        return;
    }
    
    if( buf[i] == 't' )
    {
        HalLedSet(HAL_LED_4,HAL_LED_MODE_TOGGLE);
        HAL_LED_LOG("LED TOGGLE");
        return;
    }


    //flash or breath led
    if( buf[i] == 'F' || buf[i] == 'B')
    {
        mode = ( buf[i] == 'F' ? HAL_LED_MODE_BLINK : HAL_LED_MODE_BREATH );
        i++;
        for(; buf[i]==' ' && i<len ; i++);
        for(; i<len; i++)
        {

            if(buf[i]==' ' || buf[i]=='\n')
            {
                status++;
                for(; buf[i]==' ' && i<len ; i++);
                if( i==len ) break;
            }

            if( status == 0)
            {

                if(buf[i]=='X')
                {

                    led_num = 0xff;
                }
                else
                {
                    if(hal_led_test_is_num(buf[i]))
                    {
                        led_num *= 10;
                        led_num += (buf[i]-'0');
                    }
                    else
                    {
                        HAL_LED_LOG_ERROR(" Wrong led_num, It has to be a number or 'X' ");
                        return ;
                    }
                }


            }
            else if( status == 1)
            {

                if(hal_led_test_is_num(buf[i]))
                {
                    priod *= 10;
                    priod += (buf[i]-'0');
                }
                else
                {
                    HAL_LED_LOG_ERROR(" Wrong period, It has to be a number ");
                    return ;
                }

            }
            else if(status == 2)
            {

                if(hal_led_test_is_num(buf[i]))
                {
                    duty *= 10;
                    duty += (buf[i]-'0');
                }
                else
                {
                    HAL_LED_LOG_ERROR(" Wrong duty, It has to be a number ");
                    return ;
                }

            }
            else if(status == 3)
            {

                if(hal_led_test_is_num(buf[i]))
                {
                    cycle *= 10;
                    cycle += (buf[i]-'0');
                }
                else
                {
                    HAL_LED_LOG_ERROR(" Wrong cycle, It has to be a number ");
                    return ;
                }

            }

            flag |= (1<<status);
        }

        if( (flag & 0xf) != 0xf)
        {

            HAL_LED_LOG_ERROR(" Wrong number of parameters  ");
            hal_led_test_print_help();
            return;

        }

        if( led_num == 0xff)
        {

            for( j=0; j<4; j++ )
            {

                if( mode == HAL_LED_MODE_BREATH )
                {
                    HalLedBreath(1<<j, cycle, duty, priod);
                }
                
                if( mode == HAL_LED_MODE_BLINK )
                {
                    HalLedBlink(1<<j, cycle, duty, priod);
                }


            }

        }
        else
        {
            
            if( mode == HAL_LED_MODE_BREATH )
            {
                HalLedBreath(1<<led_num, cycle, duty, priod);
            }
            
            if( mode == HAL_LED_MODE_BLINK )
            {
                HalLedBlink(1<<led_num, cycle, duty, priod);
            }

        }

        HAL_LED_LOG("HAL LED EXEC SUCCESS");


    }
    else
    {

        HAL_LED_LOG_ERROR("Unknow Cmd , See the test instructions below  ");
        hal_led_test_print_help();
    }


}

#endif









/**************************************************************************************************
 * @fn      HalLedMsgCallBackHandler
 *
 * @brief   handler the halled msg
 *
 * @param   none
 *
 * @return  None
 **************************************************************************************************/
void HalLedMsgCallBackHandler(uint8 leds, uint8 event){
    
    switch(event)
    {
        case HalLedNeedPower:
            
            osal_pwrmgr_task_state( Test_TaskID, PWRMGR_HOLD);
            LOG("HalLedNeedPower");
            break;
        
        case HalLedNotNeedPower:
            
            osal_pwrmgr_task_state( Test_TaskID, PWRMGR_CONSERVE);
            LOG("HalLedNotNeedPower");
            break;
        
        default:
            break;
    
    }

};


/**************************************************************************************************
 * @fn      Hal_Init
 *
 * @brief   Hal Initialization function.
 *
 * @param   task_id - Hal TaskId
 *
 * @return  None
 **************************************************************************************************/
void Test_Led_Init( uint8 task_id )
{
  
    
  /* Register task ID */
  Test_TaskID = task_id;
  osal_start_reload_timer(task_id, TASK_TIME_EVT_1S, 1000 );
  osal_start_timerEx(task_id, TASK_LOWPOER_ENTER_EVT, 4000 );
  //HalLedSet(HAL_LED_4,HAL_LED_MODE_OFF);
  //HalLedBreath(HAL_LED_4, 3, 50, 1000);
  HalLedCallbackReg(HalLedMsgCallBackHandler);  
  
  LOG("test task led start, %d", task_id);
  
    osal_pwrmgr_task_state( task_id, PWRMGR_HOLD);
  
}




/**************************************************************************************************
 * @fn      Test_ProcessEvent
 *
 * @brief   Test Process Event
 *
 * @param   task_id - Hal TaskId
 *          events - events
 *
 * @return  None
 **************************************************************************************************/
uint16 Test_Led_ProcessEvent( uint8 task_id, uint16 events )
{
  uint8 *msgPtr;
    
  uint16 rdm = 0;
  uint8  size =0;
  uint8  tar_task;
  
  (void)task_id;  // Intentionally unreferenced parameter

  if ( events & SYS_EVENT_MSG )
  {
        msgPtr = osal_msg_receive(task_id);

        while (msgPtr)
        {
          /* Do something here - for now, just deallocate the msg and move on */
            
          LOG("T %02d, %s", task_id,msgPtr);

          /* De-allocate */
          osal_msg_deallocate( msgPtr );
          /* Next */
          msgPtr = osal_msg_receive( task_id );
        }
      return (events ^ SYS_EVENT_MSG );
  }
  
  
  if ( events & TASK_TIME_EVT_1S )
  {
      //osal_set_event(task_id, TASK_TIME_EVT_PRINT);
      size = SEGGER_RTT_Read(0, rttBuffer, sizeof(rttBuffer));
      
      if(size) 
      {
            hal_led_test_by_uart(rttBuffer,size);

      }

      
      return (events ^ TASK_TIME_EVT_1S );
  }
  
  if ( events & TASK_LOWPOER_ENTER_EVT )
  {
      osal_pwrmgr_task_state( task_id, PWRMGR_CONSERVE);
      return ( events ^ TASK_LOWPOER_ENTER_EVT );
  }
  

   return 0;
}



